﻿using System;
using System.Windows.Automation;
using QuickUIT.Utilities;

namespace QuickUIT
{
    /// <summary>
    /// Matches an <see cref="AutomationProperty"/> on a <see cref="AutomationElement"/> by an exact value.
    /// </summary>
    public class AutomationElementExactSearchCondition : IAutomationElementSearchCondition
    {
        /// <summary>
        /// Gets the property to be matched. 
        /// </summary>
        public AutomationProperty Property
        {
            get { return _property; }
        }

        /// <summary>
        /// Gets the value to look for in the property. 
        /// </summary>
        public object Value
        {
            get { return _value; }
        }

        private readonly AutomationProperty _property;
        private readonly object _value;

        /// <summary>
        /// Creates a new search condition which matches properties by an exact value. 
        /// </summary>
        /// <param name="property">The property to match.</param>
        /// <param name="value">The value to match the property by.</param>
        public AutomationElementExactSearchCondition(AutomationProperty property, object value)
        {
            ValidationUtility.ValidateArgumentNotNull(property, "property");
            _property = property;
            _value = value;
        }

        /// <summary>
        /// Indicates whether an <see cref="AutomationElement"/> matches the search condition.  
        /// </summary>
        /// <param name="element">The element to check.</param>
        /// <returns>True if the search condition matches a property on the element; otherwise, false.</returns>
        public bool Matches(AutomationElement element)
        {
            object value = element.GetCurrentPropertyValue(_property);
            return _value.Equals(value);
        }

        /// <summary>
        /// Returns a string that represents the current object.
        /// </summary>
        /// <returns>A string that represents the current object.</returns>
        public override string ToString()
        {
            string property = Property.ProgrammaticName.Split('.')[1];
            string value = Value != null ? Value.ToString() : String.Empty;
            var controlType = Value as ControlType;
            if (controlType != null)
            {
                value = controlType.ProgrammaticName.Split('.')[1];
            }
            return String.Format("{0}='{1}'", property.Replace("Property", String.Empty), value); 
        }
    }
}
